<?php
/**
 * Created by PhpStorm.
 * User: wangsentao
 * Date: 2018/3/6
 * Time: 下午5:51
 */

namespace app\open\controller;

use app\common\Model\Order;
use app\common\Model\UserBalance;
use app\common\ShaoHuoPay\Gateways\Wechat\WxTools;
use app\common\ShaoHuoPay\Pay;
use app\api\service\JpushService;

class Wxmini
{
    protected $config;

    public function __construct()
    {
        $this->config = [
            'appid' => config('pay')['WX_PAY']['APPID'], // APP APPID
            'app_id' => config('pay')['WX_MP_PAY']['APPID'], // 公众号 APPID
            'miniapp_id' => config('pay')['WX_WECHAT_PAY']['APPID'], // 小程序 APPID
            'mch_id' => config('pay')['wx_mchid_mini'],
            'key' => config('pay')['wx_key_mini'],
            'notify_url' => config('pay')['wx_notiful_mini'],
            'cert_client' => '', // optional，退款等情况时用到
            'cert_key' => '',// optional，退款等情况时用到
            //'mode'          => 'dev', // optional
        ];
    }

    public function notify()
    {
        $pay = Pay::wechat($this->config);

        try {
            $data = $pay->verify(); //验证
            $orderinfo = $data->all();

            $sys_orderinfo = Order::getOrderInfoByOrderNumOrId($orderinfo['out_trade_no'], '');

            //检测金额
            if ($sys_orderinfo['code'] != 'success') {

                return false;
            }
            WLog('wx_back_param.txt', json_encode($data->all()));

            //根据订单类型更新充值或者支付
            if ($orderinfo['result_code'] == 'SUCCESS') {

                if ($sys_orderinfo['data']['order_type'] == 1) {

                    //支付成功后推送
                    JpushService::instance()->makeOrder($sys_orderinfo['data']['order_id']);

                    $res = Order::updateShaoHuoOrder($sys_orderinfo['data']['uid'], $orderinfo['out_trade_no'], $sys_orderinfo['data']['order_id'], $orderinfo['transaction_id']);
                    if ($res['code'] == 'success') {
                        return $pay->success()->send();
                    }
                }

                if ($sys_orderinfo['data']['order_type'] == 4) {//充值
                    $res = Order::updateRechargeOrder($sys_orderinfo['data']['uid'], $orderinfo['out_trade_no'], $orderinfo['transaction_id'], $sys_orderinfo['data']['amount'] );
                    if ($res['code'] == 'success') {
                        return $pay->success()->send();
                    }
                }
            }

        } catch (\Exception $e) {
            WLog('wx_back_error.txt', $e->getMessage());
        }
    }
}